from SimpleXMLRPCServer import SimpleXMLRPCServer
from os import path
import os

import dbus
import hashlib
from datetime import datetime

home = os.path.expanduser("~")
home_dir = home + "/.qlive/phone"
account_info_file = path.join(home_dir,"account_info.qlive")

class Caller :
	def __init__(self) :
		self.server = SimpleXMLRPCServer (("localhost", 9191))
		self.acc_id = self.getAccountId()
		self.call_mgr, self.conf_mgr = self.getCallManager()

	def debug(self, message):
		print "[Caller] --", message

	def start(self):
		self.server.register_function(self.placeCall)
		self.server.register_function(self.hangUp)
		self.server.register_function(self.answerCall)
		self.server.register_function(self.getCodecList)

		self.debug("start server @localhost 9191 forever ...")
		self.server.serve_forever()

	def getAccountId(self):
		global account_info_file
		acc_file = open(account_info_file, "r")
		acc_id = acc_file.readline()
		return acc_id

	def getCallManager(self):
		session = dbus.SessionBus()
		call_obj = session.get_object("org.sflphone.SFLphone", "/org/sflphone/SFLphone/CallManager")  
		call_mgr = dbus.Interface(call_obj ,"org.sflphone.SFLphone.CallManager")

		conf_obj = session.get_object("org.sflphone.SFLphone", "/org/sflphone/SFLphone/ConfigurationManager")
		conf_mgr = dbus.Interface(conf_obj ,"org.sflphone.SFLphone.ConfigurationManager")
		
		return call_mgr, conf_mgr
	
	def placeCall(self, target_id) :
		self.debug("calling " + str(target_id))
		self.debug("my account id -> " + str(self.acc_id))

		h = hashlib.new("ripemd160")
		h.update(str(datetime.now()))
		call_id = h.hexdigest()

		# generate call id ########
		try :

			acc_id = self.getAccountId()
			self.call_mgr.placeCall(acc_id, call_id, target_id)
			print "place calll acc_id=%s, call_id=%s, target_id=%s" % (acc_id, call_id, target_id)
		except Exception as ex :
			self.debug("place call error " + str(ex))
			return False

		return True

	def hangUp(self) :
		call_id = self.call_mgr.getCurrentCallID()
		self.call_mgr.hangUp(call_id)
		return str(call_id)

	def answerCall(self, call_id):
		self.debug("answer call from " + call_id)
		self.call_mgr.accept(call_id)
		return 1

	def getCodecList(self):
		codecs_detail = {}
		codecs = self.conf_mgr.getCodecList()

		for codec in codecs :
			details = self.conf_mgr.getCodecDetails(int(codec))
			data = {}
			data["NAME"] = str(details[0])
			data["FREQUENCY"] = str(details[1])
			data["BITRATE"] = str(details[2])
			data["BANDWIDTH"] = str(details[3])
			codecs_detail[str(codec)] = data
		return codecs_detail

if __name__ == "__main__" :
	caller = Caller()
	caller.start()
		

	
